package com.springboot.demo.controller;


import cn.hutool.core.util.StrUtil;
import com.cx.item.common.par.check.CheckParTarget;
import com.cx.item.common.par.check.CheckParTargetInstance;
import com.cx.item.common.vo.ResultPageVo;
import com.springboot.demo.model.par.WechatPayPar;
import com.springboot.demo.model.vo.WechatLoginVo;
import com.springboot.demo.service.WechatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by hwm on 2018/6/28.
 */
@Api(description = "微信api")
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WechatService wechatService;

    @ApiOperation("微信登陆&注册")
    @RequestMapping(value = "/wechatLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultPageVo<WechatLoginVo> wechatLogin(String code) {

        if (StrUtil.isEmpty(code)) {
            return ResultPageVo.failure("code为空", null);
        }

        WechatLoginVo wechatLoginVo = wechatService.wechatLogin(code);

        return ResultPageVo.success(wechatLoginVo);
    }

    @ApiOperation("微信支付")
    @RequestMapping(value = "/wechatPay", method = RequestMethod.POST)
    @ResponseBody
    public ResultPageVo<Map<String, String>> wechatPay(WechatPayPar wechatPayPar, HttpServletRequest request) {

        CheckParTarget instance = CheckParTargetInstance.getInstance(wechatPayPar, "orderId", "payPrice");
        instance.checkParIsNullThrowError();

        Map<String, String> wechatPay = wechatService.wechatPay(wechatPayPar, request);

        return ResultPageVo.success(wechatPay);
    }

    /**
     * 微信支付回调（微信调用）
     *
     * @param request
     * @param response
     * @return
     * @Title: wechatNotify
     */
    @ApiOperation("微信支付回调（微信调用）")
    @RequestMapping(value = "/wechatNotify", method = RequestMethod.POST)
    @ResponseBody
    public void wechatNotify(HttpServletRequest request, HttpServletResponse response) {

        log.debug("====>微信支付成功回调方法,由微信发起");
        log.debug("====>微信支付成功回调方法,由微信发起");
        log.debug("====>微信支付成功回调方法,由微信发起");

        try {
            wechatService.wechatNotify(request, response);
        } catch (Exception e) {
            log.error("error微信支付回调失败", e);
        }
    }
}
